package org.lee.jfc.pie;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;

import javax.swing.*;
import java.awt.*;

/**
 * PieChartDemo
 * 饼图
 *
 * @author dralee
 * @date 2021-12-29 15:28:08
 **/
public class PieChartDemo extends JFrame {
    public PieChartDemo() throws HeadlessException {
        initUI();
    }

    private void initUI() {
        DefaultPieDataset dataset = createDataset();
        JFreeChart chart = createChart(dataset);
        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        chartPanel.setBackground(Color.white);
        add(chartPanel);

        pack();
        setTitle("Line chart");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private JFreeChart createChart(DefaultPieDataset dataset) {
        JFreeChart chart = ChartFactory.createPieChart("Web servers market share",
                dataset, false, true, false);
//        chart.setTitle(new TextTitle("Average Salary per Age", new Font("Serif", Font.BOLD, 18)));
        return chart;
    }

    private DefaultPieDataset createDataset() {
        DefaultPieDataset dataset = new DefaultPieDataset();
        dataset.setValue("Apache", 52);
        dataset.setValue("Nginx", 31);
        dataset.setValue("IIS", 12);
        dataset.setValue("LiteSpeed", 2);
        dataset.setValue("Google server", 1);
        dataset.setValue("Others", 2);

        return dataset;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new PieChartDemo().setVisible(true));
    }
}
